package com.dzsw.order.service;

import com.dzsw.order.feign.ItemFeignClient;
import com.dzsw.properties.ItemProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class ItemService {

    // Spring框架对RESTful方式的http请求做了封装，来简化操作
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ItemProperties itemProperties;

    @Resource
    private ItemFeignClient itemFeignClient;

    public Map<String, Object> queryItemById1(Long id) {
        return this.restTemplate.getForObject(itemProperties.getUrl() + id, Map.class);
    }

    public Map<String, Object> queryItemById2(Long id) {
        // 该方法走eureka注册中心调用(去注册中心根据app-item查找服务，这种方式必须先开启负载均衡@LoadBalanced)
        String itemUrl = "http://app-item/item/query/{id}";
        Map<String, Object> result = restTemplate.getForObject(itemUrl, Map.class, id);
        System.out.println("[queryItemById2-线程池名称]=>" + Thread.currentThread().getName() + "订单系统调用商品服务,result:" + result);
        return result;
    }

    @HystrixCommand(fallbackMethod = "queryItemByIdFallbackMethod")
    public Map<String, Object> queryItemById3(Long id) {
        // 该方法走eureka注册中心调用(去注册中心根据app-item查找服务，这种方式必须先开启负载均衡@LoadBalanced)
        String itemUrl = "http://app-item/item/query/{id}";
        Map<String, Object> result = restTemplate.getForObject(itemUrl, Map.class, id);
        System.out.println("[HystrixCommand queryItemById3-线程池名称]=>" + Thread.currentThread().getName() + "订单系统调用商品服务,result:" + result);
        return result;
    }

    public Map<String, Object> queryItemById4(Long id) {
        Map<String, Object> result = itemFeignClient.queryItemById(id);
        System.out.println("[Feign HystrixCommand queryItemById4-线程池名称]=>" + Thread.currentThread().getName() + "订单系统调用商品服务,result:" + result);
        return result;
    }

    /**
     * 请求失败执行的方法
     * fallbackMethod的方法参数个数类型要和原方法一致
     *
     * @param id
     * @return
     */
    public Map<String, Object> queryItemByIdFallbackMethod(Long id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("title", "查询商品信息出错!");
        return map;
    }
}
